package com.xxr.mom.ci.common.dto;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.xxr.mom.ci.common.exception.BusinessException;
import com.xxr.mom.ci.common.exception.InterworkingException;
import com.xxr.mom.ci.common.enums.InterworkingRetEnum;
import com.xxr.mom.ci.common.util.EncryptionDecryptionUtil;
import lombok.Data;

import java.io.Serializable;

/**
 * 2016版 返回结果
 * @author natsuki_kining
 */
@Data
public class InterworkingResult implements Serializable {

    private static final long serialVersionUID = 1L;

    /**
     * 返回编码
     * {@link InterworkingRetEnum}
     */
    @JsonProperty("Ret")
    private Integer ret;

    /**
     * 返回信息
     */
    @JsonProperty("Msg")
    private String msg;

    /**
     * 签名
     */
    @JsonProperty("Sig")
    private String sig;

    /**
     * 返回数据
     */
    @JsonProperty("Data")
    private String data;

    public InterworkingResult() {
    }

    public static InterworkingResult getInterworkingResult(InterworkingRetEnum retEnum) {
        InterworkingResult result = new InterworkingResult();
        result.ret = retEnum.getRet();
        result.msg = retEnum.getDesc();
        return result;
    }

    public static InterworkingResult getInterworkingResult(InterworkingRetEnum retEnum, String message) {
        InterworkingResult result = new InterworkingResult();
        result.ret = retEnum.getRet();
        result.msg = message;
        return result;
    }

    /**
     * 请求成功返回
     *
     * @param data
     * @return
     */
    public static InterworkingResult success(EncryptionDecryptionDto encrypt, String data) {
        InterworkingResult interworkingResult = getInterworkingResult(InterworkingRetEnum.SUCCESS);
        interworkingResult.setData(data);
        interworkingResult.setSig(EncryptionDecryptionUtil.sign(encrypt.getSigSecret(), data));
        return interworkingResult;
    }

    public static InterworkingResult error(Exception e) {
        if (e instanceof InterworkingException) {
            InterworkingResult result = new InterworkingResult();
            InterworkingException interworkingException = (InterworkingException) e;
            result.ret = interworkingException.getCode();
            result.msg = interworkingException.getMessage();
            return result;
        }
        if (e instanceof BusinessException) {
            InterworkingResult result = new InterworkingResult();
            BusinessException businessException = (BusinessException) e;
            result.ret = InterworkingRetEnum.SYSTEM_ERROR.getRet();
            result.msg = businessException.getMessage();
            return result;
        }
        return InterworkingResult.getInterworkingResult(InterworkingRetEnum.SYSTEM_ERROR);
    }

}
